<?php
namespace App\Http\Controllers\Admin;

use App\Models\Areas;
use App\Models\AuthGroup;
use App\Models\Category;
use App\Models\NewAdmin;
use App\Models\ShopUser;
use App\Models\ShopUserLog;
use App\Services\EsignService;
use App\Services\CommonService;
use App\Services\EsignV3Service;
use App\Services\OtherCallbacksService;
use App\Services\AntchainService;
use Illuminate\Http\Request;

//供应商审核
class SupplierCheckController extends BaseController
{
    //供应商审核列表POST http://shop.cn/Admin/SupplierCheck/supplierCheckList
    public function supplierCheckList(Request $request)
    {
        $input = $request->input();
        $where = [];
        $where[] = ['su.is_delete', ShopUser::SHOP_USER_NOT_DELETE];
        if (!empty($input['shopname'])) {
            $where[] = ['su.shopname', 'like', '%' . trim($input['shopname']) . '%'];
        }
        if (!empty($input['account_num'])) {
            $where[] = ['oa.mobile', 'like', '%' . trim($input['account_num']) . '%'];
        }
        if (!empty($input['addtime'])) {
            $time = searchTime($input['addtime']);
            $where[] = ['su.addtime', '>=', strtotime($time['begin_time'])];
            $where[] = ['su.addtime', '<', strtotime($time['end_time'])];
        }
        //状态：1已审核 2待审核
        switch ($input['status']) {
            case '1'://已审核
                $status_where[] = ['su.status', ShopUser::SHOP_USER_STATUS_IS_CHECK];
                break;
            case '2'://待审核
                $status_where[] = ['su.status', ShopUser::SHOP_USER_STATUS_NOT_CHECK];
                break;

            default://全部
                $status_where = [];
                break;
        }
        $page = $input['page'] ? $input['page'] : 1;
        $pageSize = $input['pageSize'] ? $input['pageSize'] : CommonService::PAGESIZE;
        $data = ShopUser::GetSupplierCheckList($pageSize, $where, $status_where);
        $data = formatPage($data);
        $info = $data['data'];
        foreach ($info as $k => $v) {
            $info[$k]['addtime'] = !empty($v['addtime']) ? dateFormat($v['addtime']) : '';
        }
        $data['data'] = $info;
        //计算数量
        $data['count']['status_total'] = ShopUser::GetSupplierStatusCount($where, []);
        $data['count']['notcheck_status_total'] = ShopUser::GetSupplierStatusCount($where, array('su.status' => ShopUser::SHOP_USER_STATUS_NOT_CHECK));
        $data['count']['istcheck_status_total'] = ShopUser::GetSupplierStatusCount($where, array('su.status' => ShopUser::SHOP_USER_STATUS_IS_CHECK));
        return ReturnMsg(CommonService::HTTP_CODE_SUCCESS, '获取成功', $data);
    }

    //根据id编辑审核状态(通过)
    public function editShopUserStatus(Request $request)
    {
        $input = $request->input();
        if (empty($input['id'])) {
            return ReturnMsg(CommonService::HTTP_CODE_FAIL, 'id为空');
        }
        $res = ShopUser::editShopUserById($input['id'], array('status' => $input['status']));
        if (!$res) {
            return ReturnMsg(CommonService::HTTP_CODE_FAIL, '审核失败');
        }
        $shopUser = ShopUser::GetShopUser(array('id' => $input['id']));
        $other_auth_group = AuthGroup::GetOneAuthGroup(array('rules' => '*', 'type' => AuthGroup::AUTH_GROUP_TYPE_SHOPER, 'user_id' => '0'));
        $pwd = substr($shopUser['contact_tel'], -6);
        $other_admin_data = array(
            'username' => $shopUser['people'],
            'mobile' => $shopUser['contact_tel'],
            'password' => md5($shopUser['contact_tel'] . md5($pwd)),
            'role_id' => $other_auth_group['id'],
            'user_id' => $shopUser['member_id'],
            'type' => NewAdmin::OTHER_ADMIN_TYPE_SHOPER,
            'create_time' => date('Y-m-d H:i:s'),
        );
        $add_res = NewAdmin::insert($other_admin_data);
        if (!$add_res) {
            return ReturnMsg(CommonService::HTTP_CODE_FAIL, '审核失败：账号添加失败');
        }

        $res = $this->createEsign($input['id']);
        if($res ){
            ShopUser::editShopUserById($input['id'], array('endisable' => ShopUser::SHOP_USER_ENABLE));
            //添加操作记录
            ShopUserLog::addLog($this->users['id'], $shopUser['member_id'], 1, '供应商入驻审核', [], [], '审核通过');

            return ReturnMsg(CommonService::HTTP_CODE_SUCCESS, '审核成功');
        }else{
            return ReturnMsg(CommonService::HTTP_CODE_FAIL, '合同账号生成失败');
        }
    }

    //根据id删除供应商信息
    public function delShopUser(Request $request)
    {
        $input = $request->input();
        if (empty($input['id'])) {
            return ReturnMsg(CommonService::HTTP_CODE_FAIL, 'id为空');
        }
        ShopUser::editShopUserById($input['id'], array('is_delete' => ShopUser::SHOP_USER_IS_DELETE));
        //添加操作记录
        $shopUser = ShopUser::GetShopUser(array('id' => $input['id']));
        ShopUserLog::addLog($this->users['id'], $shopUser['member_id'], 1, '删除供应商', [], [], '');
        return ReturnMsg(CommonService::HTTP_CODE_SUCCESS, '删除成功');
    }

    //根据id查看供应商信息
    public function shopUserById(Request $request)
    {
        $input = $request->input();
        if (empty($input['id'])) {
            return ReturnMsg(CommonService::HTTP_CODE_FAIL, 'id为空');
        }
        $shopUser = ShopUser::GetShopUser($where = array('id' => $input['id']));
        $category = Category::GetParentCateById($shopUser['category_id']);
        $shopcity = $shopUser['shopcity'];
        if (empty($shopcity)) {
            $shopcity_prov_id = '';
            $shopcity_city_id = '';
            $shopcity_area_id = '';
        } else {
            $shopcity = explode('-', $shopcity);
            $prov_data = !empty($shopcity[0]) ? Areas::GetAreasByName(array('name' => $shopcity[0])) : '';
            $city_data = !empty($shopcity[1]) ? Areas::GetAreasByName(array('name' => $shopcity[1])) : '';
            $area_data = !empty($shopcity[2]) && !empty($city_data['id']) ? Areas::GetAreasByName(array('name' => $shopcity[2], 'pid' => $city_data['id'])) : '';
            $shopcity_prov_id = !empty($prov_data['id']) ? $prov_data['id'] : '';
            $shopcity_city_id = !empty($city_data['id']) ? $city_data['id'] : '';
            $shopcity_area_id = !empty($area_data['id']) ? $area_data['id'] : '';
        }
        $company_area = $shopUser['company_area'];
        if (empty($company_area)) {
            $prov_id = '';
            $city_id = '';
            $area_id = '';
        } else {
            $company_area = explode('-', $company_area);
            $prov_data = !empty($company_area[0]) ? Areas::GetAreasByName(array('name' => $company_area[0])) : '';
            $city_data = !empty($company_area[1]) ? Areas::GetAreasByName(array('name' => $company_area[1])) : '';
            $area_data = !empty($company_area[2]) && !empty($city_data['id']) ? Areas::GetAreasByName(array('name' => $company_area[2], 'pid' => $city_data['id'])) : '';
            $prov_id = !empty($prov_data['id']) ? $prov_data['id'] : '';
            $city_id = !empty($city_data['id']) ? $city_data['id'] : '';
            $area_id = !empty($area_data['id']) ? $area_data['id'] : '';
        }
        $shopUserLog = ShopUserLog::GetLog(array('member_id' => $shopUser['member_id']));
        $operationRecord = array();
        foreach ($shopUserLog as $sulk => $sulv) {
            $arr["operation_content"] = $sulv['content'];
            $arr["operator"] = !empty($sulv['admin_id']) ? NewAdmin::GetNewAdminById($sulv['admin_id'])['username'] : $shopUser['contact_tel'];
            $arr["operation_time"] = $sulv['create_time'];
            $operationRecord[] = $arr;
        }
        $data = array(
            'shopInfo' => array(
                'photo' => $shopUser['photo'], //店铺头像
                'shopname' => $shopUser['shopname'], //店铺名称
                'category_id' => $shopUser['category_id'],
                'category_name' => isset($category['name']) ? $category['name'] : '', //经营项目
                'account' => $shopUser['account'],//账户类型
                'account_type' => $shopUser['account_type'],//是否风控
                'faptype' => $shopUser['faptype'],//发票类型
                'shopcity_prov_id' => $shopcity_prov_id,
                'shopcity_city_id' => $shopcity_city_id,
                'shopcity_area_id' => $shopcity_area_id,
                'shopcity' => $shopUser['shopcity'], //当前经营位置
                'people' => $shopUser['people'], //店铺联系人
                'contact_tel' => $shopUser['contact_tel'], //联系人手机号
                'status' => $shopUser['status'], //状态：1已审核 2待审核
            ),
            'companyInfo' => array(
                'mechanism' => $shopUser['mechanism'], //公司名称
                'companyid' => $shopUser['companyid'], //工商注册号
                'prov_id' => $prov_id,
                'city_id' => $city_id,
                'area_id' => $area_id,
                'company_area' => $shopUser['company_area'], //公司所在区域
                'company' => $shopUser['company'], //公司地址
                'faname' => $shopUser['faname'], //法人姓名
                'idcard' => $shopUser['idcard'], //法人身份证号
                'shopcard' => $shopUser['shopcard'], //营业执照
                'doorphoto' => $shopUser['doorphoto'], //公司门头照
                'seal_url' => $shopUser['seal_url'], //公章图片
                'faidcard' => $shopUser['faidcard'], //身份证正面照
                'faidcard_back' => $shopUser['faidcard_back'], //身份证反面照
            ),
            'operationRecord' => $operationRecord,
        );
        return ReturnMsg(CommonService::HTTP_CODE_SUCCESS, '获取成功', $data);
    }

    //根据id编辑供应商信息
    public function editShopUserById(Request $request)
    {
        $input = $request->input();
        if (empty($input['id'])) {
            return ReturnMsg(CommonService::HTTP_CODE_FAIL, 'id为空');
        }
        if (empty($input['photo']) || empty($input['shopname']) || empty($input['account']) || empty($input['account_type'])
            || empty($input['faptype']) || empty($input['shopcity']) || empty($input['people']) || empty($input['contact_tel'] || empty($input['mechanism']))
            || empty($input['companyid']) || empty($input['company_area']) || empty($input['company']) || empty($input['faname'] || empty($input['idcard']))
            || empty($input['shopcard']) || empty($input['doorphoto']) || empty($input['seal_url']) || empty($input['faidcard']) || empty($input['faidcard_back'])) {
            return ReturnMsg(CommonService::HTTP_CODE_FAIL, '缺少参数');
        }
        $select = array('member_id', 'id', 'photo', 'shopname', 'account', 'account_type', 'faptype', 'shopcity', 'people', 'contact_tel',
            'mechanism', 'companyid', 'company_area', 'company', 'faname', 'idcard', 'shopcard', 'doorphoto', 'seal_url', 'faidcard', 'faidcard_back', 'esign_seal_id');
        $shopUser = ShopUser::select($select)->where(array('id' => $input['id']))->first();
        $shopUser = $shopUser ? $shopUser->toArray() : array();
        $member_id = $shopUser['member_id'];
        unset($shopUser['member_id']);
        $before_data = array_diff_assoc($shopUser, $input); //比较两个数组的键和值，并返回差集
        $after_data = array_diff_assoc($input, $shopUser);
        if (empty($before_data)) {
            return ReturnMsg(CommonService::HTTP_CODE_FAIL, '数据未发生变化');
        }
        if (!Verify_Phone($input['contact_tel'])) {
            return ReturnMsg(CommonService::HTTP_CODE_FAIL, '请输入有效联系人手机号');
        }
        if (!isBusinessRegistrationNumber($input['companyid'])) {
            return ReturnMsg(CommonService::HTTP_CODE_FAIL, '请输入有效工商注册号');
        }
        if (!check_passportid($input['idcard'])) {
            return ReturnMsg(CommonService::HTTP_CODE_FAIL, '请输入有效法人身份证号');
        }
        ShopUser::editShopUserByid($input['id'], $after_data);
        //添加操作记录
        ShopUserLog::addLog($this->users['id'], $member_id, 1, '编辑供应商', $before_data, $after_data, '');
        return ReturnMsg(CommonService::HTTP_CODE_SUCCESS, '编辑成功');
    }

    public function createAntchain($shopId){
        $flag = false;
        $shop = ShopUser::where('id',$shopId)->select('id','idcard','faname','mobile','companyid','mechanism','member_id')->first();
        $shop = obToArray($shop);
        if($shop){
            $res = AntchainService::merchatCreate($shop);
            if($res['status']){
                $ant_user_id = $res['data'];
                $shopRes = ShopUser::where('id',$shopId)->update(['ant_user_id'=>$ant_user_id]);
                if($shopRes){
                    $flag = true;
                }
            }
        }
        return $flag;
    }

    public function createEsign($shopId){
        $flag = true;
        $shop = ShopUser::where('id',$shopId)->select('id','idcard','faname','mobile','esign_shop_id','companyid','mechanism','member_id','esign_seal_id')->first();
        $shop = obToArray($shop);
        if($shop){
//            $accountId = EsignV3Service::addFaAccountID($shop['idcard'],$shop['faname'],$shop['idcard'],$shop['mobile']);
//            if($accountId){
                if(empty($shop['esign_shop_id'])){
                    $orgid = EsignV3Service::addFaAccountID($shop['companyid'],$shop['mechanism'],$shop['companyid'],$shop['mobile']);
                    if($orgid){
                        ShopUser::where('id',$shopId)->update(['esign_shop_id'=>$orgid]);
                    }else{
                        $flag = false;
                    }
                }else{
                    $orgid = $shop['esign_shop_id'];
                }
//            }
            if(empty($shop['esign_seal_id'])){
                $seal_id = EsignV3Service::addOrganizeSeals($orgid);
                if($seal_id){
                    ShopUser::where('id',$shopId)->update(['esign_seal_id'=>$seal_id]);
                }else{
                    $flag = false;
                }
            }
        }else{
            $flag = false;
        }
        return $flag;
    }



}
